package com.tqjc.system;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tqjc.business.interactivewithscan.entity.Coord;
import com.tqjc.system.common.constant.AddTaskConstant;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.RemoteURLConstant;
import com.tqjc.system.common.entity.BO.*;
import com.tqjc.system.common.enums.*;
import com.tqjc.system.common.exception.AddTaskException;
import com.tqjc.system.core.gate.constants.GateConstant;
import com.tqjc.system.core.gate.service.SysGateService;
import com.tqjc.system.core.pipeline.ProcessContext;
import com.tqjc.system.core.pipeline.ProcessMachine;
import com.tqjc.system.core.pipeline.service.CarExecuteTaskAction;
import com.tqjc.system.core.pipeline.thread.CarDoingAddTaskThread;
import com.tqjc.system.core.pipeline.thread.CarDoingSingleAddTaskThread;
import com.tqjc.system.core.pipeline.thread.CarProgressLogThread;
import com.tqjc.system.core.pipeline.thread.SendTankPositionThread;
import com.tqjc.system.core.pipeline.util.AddTaskUtil;
import com.tqjc.system.core.pipeline.util.ScanUtils;
import com.tqjc.system.core.task.CarPhotoManageTask;
import com.tqjc.system.core.threadpool.ThreadPoolManager;
import com.tqjc.system.core.util.HttpsUtils;
import com.tqjc.system.core.util.PLCHttpsUtils;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.system.system.asyn.AsynTaskExecuteThread;
import com.tqjc.system.system.dao.SysGateRecordDao;
import com.tqjc.system.system.entity.SysAreaInfoEntity;
import com.tqjc.system.system.entity.SysGateRecordEntity;
import com.tqjc.system.system.service.SysAddDetailTaskService;
import com.tqjc.system.system.service.SysAreaInfoService;
import com.tqjc.system.system.service.SysGateRecordService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 86195
 * @version 1.0
 * @description TODO
 * @date 2023/9/21 10:09
 */
@SpringBootTest(classes = XiangGangApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Slf4j
public class Mytest {



    @Autowired
    private SysGateRecordDao sysGateRecordDao;

    @Autowired
    private SysAreaInfoService areaInfoService;

    @Autowired
    private SysGateService service;

    @Autowired
    private SysAddDetailTaskService  detailTaskService;

    @Autowired
    private CarPhotoManageTask task;

    @Autowired
    private CarExecuteTaskAction carExecuteTaskAction;

    @Autowired
    private SysGateRecordService gateRecordService;

    @Test
    public void testCarNo(){
        String strNumber = "湘A123456";
        String s = buildParamStr(strNumber, 10);
        System.out.println("结果是"+s);


    }


    /**
     * 测试库区
     */
    @Test
    public void testTankThread(){
        try {

            Coord spanGrabPoint = ScanUtils.getAreaPointBO(AddTaskConstant.DREGS_STEEL_SPAN_NO, "122", 0);
//            CarDoingAddTaskThread carDoingAddTaskThread = new CarDoingAddTaskThread();
//            carDoingAddTaskThread.goSafePosition(CarPLCInfoEnum.DREGS_STEEL_NO_2);
//            CarPLCInfoEnum.checkCarData("1号废钢跨天车大车目标坐标",CarPLCInfoEnum.WASTE_STEEL_NO_1.getMacSN(), "110");
        } catch (Exception e){

        }


    }


    /**
     * 单线程测试
     */
    @Test
    public void testSingleThread(){
        try {

            //todo  更高槽车  天车  库区   物料areaNum   物料编码    三号槽车的左右位置
            SingleTaskMaterialBO singleTaskMaterialBO = SingleTaskMaterialBO.builder().taskId("1").materialNo("122")
                    .tankCarNo("3").idKey(9L).carEnum(CarEnum.CAR_NO_1)
                    .workingSpanNo(AddTaskConstant.DREGS_STEEL_SPAN_NO).areaNum(7).build();
            CarDoingSingleAddTaskThread carDoingSingleAddTaskThread = new CarDoingSingleAddTaskThread(singleTaskMaterialBO, false, false);
//            ThreadPoolManager.getInstance().execute(new CarDoingSingleAddTaskThread(singleTaskMaterialBO,false,true));
            Thread.sleep(30000*1000);

        } catch (Exception e){
            log.error("单线程任务测试异常",e);
        }
    }


    @Test
    public void testScan(){
        try {
//            RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//            headers.set("Accept", "application/json");
//            ResponseEntity<Boolean> response = restTemplate.exchange("http://192.168.2.35:9991/ScanTankData/SetRequestID?reqID=A1N20240105175011", HttpMethod.POST, null, Boolean.class);
//            String redirectUrl = response.getHeaders().getLocation().toString();
//
//            // Make a new request to the redirected URL
//            response = restTemplate.exchange(redirectUrl, HttpMethod.POST, null, Boolean.class);


            ScanUtils.startAndReceiveRes(TankCarNoEnum.NO_3,AddTaskConstant.DREGS_STEEL_SPAN_NO);

//            Coord tankCarPoint = ScanUtils.getTankCarPoint(TankCarNoEnum.NO_2, AddTaskConstant.WASTE_STEEL_SPAN_NO);
//            TankScanStatusResBO tankCarStatus = ScanUtils.getScannerStatus(TankCarNoEnum.NO_3.getScannerNo());
//            ScanUtils.getTankCarStatus(TankCarNoEnum.NO_1.getScannerNo());
//            MaterialSpanBO freeSpan = AddTaskUtil.getFreeSpan();

            System.out.println("结束了");
        } catch (Exception e){
            log.error("单线程任务测试异常",e);
        }
    }


    @Test
    public void testObj(){
        DropPosition d1 = new DropPosition(new Double(1),new Double(2),new Double(3),0);
        DropPosition d3 = new DropPosition(new Double(1),new Double(2),new Double(9),0);

        DropPosition d2 = new DropPosition(new Double(1),new Double(2),new Double(4),0);
        TreeSet<DropPosition> list = new TreeSet<>();
        list.add(d1);
        list.add(d3);
        list.add(d2);
        System.out.println("结束");



    }


    public static void trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Test
    public void testHttp(){
        PLCHttpsUtils.sendPost("1111",new HashMap(),ResponseLabelDataBO.class);
    }

    /***
     * @description: 测试双车联动
     **/
    @Test
    public void testDoubleThread(){
        try {
            //更改槽车  任务id   工作跨   3号槽车更改宽轨槽车位置   右边 -- "1"
            AddBusinessTaskInfo build = AddBusinessTaskInfo.builder().taskId("2").tankCarNo("2")
                    .workingSpanNo(AddTaskConstant.DREGS_STEEL_SPAN_NO).test("1").build();
            ProcessContext context = new ProcessContext();
            context.setBreakFlag(false);
            context.setProcessModel(build);
            carExecuteTaskAction.process(context);
            Thread.sleep(10000*1000);
        } catch (Exception e){
            log.error("双车联动测试案例出现异常",e);

        }

    }




    @Test
    public void testTMS()  {
        try {
            String strNumber = "钢A05692";
            String gateName = "测试";
            String filePath = "zzz";
            String fileName = "测试路径";
            SysGateRecordEntity entity = SysGateRecordEntity.builder().detailsMsg("TMS本地测试").carLicense(strNumber)
                    .gateName(gateName).filePath(filePath)
                    .status(GateRecordStatusEnum.STATUS_ABNORMAL.getStatus()) //初始化异常状态
                    .fileName(fileName).build();
            service.enter(entity);
            SysAreaInfoEntity byId = areaInfoService.getById(1);
            Random ran=new Random();
            int ranNum = ran.nextInt(4);
            System.out.println(ranNum);
        } catch (Exception e){
            log.error("测试异常",e);
        }

    }



    @Test
    public void testStr()  {
//        gateRecordService.acceptResult("钢A05692  A0000828  自产废钢,自产       五米宽厚板0000036680000001678000000199002023/12/06 16:30:33 10                              测试道  ");

        try {

            //ScanUtils.getAreaPointBO(AddTaskConstant.DREGS_STEEL_SPAN_NO,"114",0);
            Coord areaPointBO = ScanUtils.getAreaPointBO(AddTaskConstant.DREGS_STEEL_SPAN_NO, "122", 0);



        } catch (Exception e){
            log.error("异常为",e);

        }
    }





    @Test
    public void testLog()  {
        try {
            TankCarTaskInfoBO tankCarTaskInfoBO = TankCarTaskInfoBO.builder().spanNo("1").taskType("1").build();
            Queue<TankCarTaskInfoBO> tankCarTaskInfoBOS = AddTaskConstant.TANK_CAR_QUEUE_MAP.get(TankCarNoEnum.NO_1.getTankCarNo());
            tankCarTaskInfoBOS.add(tankCarTaskInfoBO);
//            SendTankPositionThread build = SendTankPositionThread.builder().tankCarNo("1").build();
//            build.start();

            Thread.sleep(1000*60);
        } catch (Exception e){
            log.error("测试异常",e);
        }

    }


    private String buildParamStr(String param,int num){
        if(StringUtils.isEmpty(param)){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        int length = param.length();
        for(int i = 0;i < num - length; i++ ){
            sb.append(" ");
        }
        sb.append(param);
        return sb.toString();
    }


    @Test
    public void test() throws Exception {




        ProcessMachine machine = SpringUtils.getBean("processMachine");
        AsynTaskExecuteThread thread = AsynTaskExecuteThread.builder().tankCarNo("2").taskId("101").machine(machine).build();
        ThreadPoolManager.getInstance().execute(thread);

        Thread.sleep(1000*60*600);




    }
//    @NoArgsConstructor
//    @AllArgsConstructor
//    @Data
//    public class testThread extends Thread{
//
//        private String threadname;
//
//        private String otherInt;
//
//        private Object object;
//
//        private ReentrantLock reentrantLock;
//
//        private int i;
//        @Override
//        public void run() {
//            String lock = AddTaskConstant.CAR_MOVE_LACK_MAP.get(AddTaskConstant.WASTE_STEEL_SPAN_NO);
//            while (true){
//                try {
//                    reentrantLock.lock();
//
//                    Thread thread = AddTaskConstant.map.get(otherInt);
//                    if(AddTaskConstant.test_num == 0){
//                        reentrantLock.unlock();
//                        synchronized (thread){
//
//                            thread.notify();
//                        }
//                        System.out.println(this.getThreadname()+"另一个线程的状态为"+thread.getState());
//                        System.out.println(getThreadname()+ "跳出循环");
//                        break;
//                    }
//                    AddTaskConstant.test_i++;
//                    i++;
//                    System.out.println("当前线程下i的值为"+AddTaskConstant.test_i);
//                    if(AddTaskConstant.test_i%2 == 0){
//                        //不冲突
//                        System.out.println(this.getThreadname()+"不冲突处理中,当前数量是:"+AddTaskConstant.test_num);
//                        AddTaskConstant.test_num = AddTaskConstant.test_num - 1;
//                        reentrantLock.unlock();
//                        State state = thread.getState();
//                        System.out.println("另一个线程的状态为"+state);
//                        synchronized (thread){
//
//                            if(state == State.WAITING){
//                                thread.notify();
//                            }
//                        }
//                        //todo 完成操作后，继续抢夺锁   等待动作完成后
//
//                        continue;
//                    } else {
//                        //冲突
//                        System.out.println(getThreadname()+ "线程等待");
//                        //写入操作，然后释放锁
//                        reentrantLock.unlock();
//                        //等待动作完成
//                        //执行事件
//                        State state = thread.getState();
//                        System.out.println("另一个线程的状态为"+state);
//                        synchronized (thread){
//
//                            if(state == State.WAITING){
//                                thread.notify();
//                            }
//                        }
//                        synchronized (this){
//
//                            this.wait();
//                        }
//                        continue;
//
//                    }
//
//
//
//                } catch (Exception e){
//                    System.out.println("出错"+e);
//                }
//
//            }
//            System.out.println(getThreadname()+"任务完成");
//        }
//
//    }
    @AllArgsConstructor
    @NoArgsConstructor
    public class GuardThread extends Thread{

        private Thread thread1;
        private Thread thread2;
        @Override
        public void run() {
            while (!(thread1.getState() == State.TERMINATED && thread2.getState() == State.TERMINATED)){
                if(thread1.getState() == State.WAITING && thread2.getState() == State.WAITING){
                    System.out.println("守护线程唤醒");
                    synchronized (thread1) {
                        if(thread1.getState() != State.TERMINATED){

                            thread1.notify();
                        }
                    }
                    synchronized (thread2){
                        if(thread2.getState() != State.TERMINATED){
                            thread2.notify();
                        }
                    }
                }
            }
        }
    }
}
